/**
 * 维护系统全局非响应式数据，包括token, clientId, lang等等。（Vuex中维护的全局UI相关的响应式数据）
 * storageType: memory, session, local
 */
import Vue from 'vue'
import { getLocalStorage, setLocalStorage, getSessionStorage, setSessionStorage, getUUID } from 'utils'
import { GLOBAL_KEY_CLIENT_ID, GLOBAL_KEY_TOKEN } from 'constants/'

const data = {}

// 获取数据
export function getData(key, storageType = 'local') {
  let value = data[key]
  if (storageType === 'local') {
    value = getLocalStorage(key)
  } else if (storageType === 'session') {
    value = getSessionStorage(key)
  }
  return value
}

// 存储数据
export function setData(key, value, storageType = 'local') {
  data[key] = value
  if (storageType === 'local') {
    value = setLocalStorage(key, value)
  } else if (storageType === 'session') {
    value = setSessionStorage(key, value)
  }
}

// 获取客户端UUID
export function getClientID() {
  let clientID = getData(GLOBAL_KEY_CLIENT_ID)
  if (!clientID) {
    clientID = getUUID()
    setData(GLOBAL_KEY_CLIENT_ID, clientID)
  }
  return clientID
}

// 获取Token
export function getToken() {
  return getData(GLOBAL_KEY_TOKEN, 'session')
}

// 设置Token
export function setToken(token) {
  setData(GLOBAL_KEY_TOKEN, token, 'session')
}

Vue.prototype.$getData = getData
Vue.prototype.$setData = setData
